<?php
namespace Wechat\Controller;
use Think\Controller;
require_once './Public/phpQuery.php';
class IndexController extends Controller {
    //微信的token
    private $token = "scunxcb";
    private $wechat = null;
    
    public function __construct() {
        $this->wechat = new \Wechat\Model\WechatReturnMsgModel();
//        $this->wechat->setUpCustomMenu();
        parent::__construct();     
    }
    
    //检测是否为微信服务器发送
    private function checkSignature(){
        $signature = I("request.signature");
        $timestamp = I('request.timestamp');
        $nonce = I('request.nonce');
        $test = new \Wechat\Model\TestModel();
        $test->create(array('value'=>"$signature|||$timestamp|||$nonce"));
        $test->add();
        $tmpArr = array($this->token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        return ($tmpStr == $signature);
    }
    
    //按照消息类型分发请求
    private function router($obj){
        $msgType = trim($obj->MsgType);
        switch ($msgType){
            case 'text':
                $this->receiveText($obj);
                break;
            case 'event':
                $this->receiveEvent($obj);
                break;
            default :
                break;
        }
    }
    
    
    //文字消息处理
    private function receiveText($obj){
        $keyword = trim($obj->Content);
        
        if ($keyword=="课表") {
            $info = $this->chkPubKey($obj);
            if (!$info){
                $this->wechat->returnBindMsg($obj);
            }else {
                $cla = new \Wechat\Model\ClaModel();
                $tmp = $cla->where("`key` = '".$obj->FromUserName."'")->getField('id');
                if (($tmp=="")or($tmp==null)){
                    if (!S(($obj->FromUserName).'doing')){
                        $this->doUpdate($obj->FromUserName);
                        S($obj->FromUserName,1,86400);
                        S(($obj->FromUserName).'doing',1,60);
                    }
                }else{
                    $this->wechat->returnClassMsg($obj,0);
                }
                
                
            }
        }else {
            $this->wechat->returnText($obj, "您的信息我们已经收到，我们会认真查看，并努力完善现有功能，感谢亲们的关注，小微将与您共同成长！");
        }
    }   

    //事件消息处理
    private function receiveEvent($obj){
        switch($obj->Event){
            case 'subscribe':
                $this->wechat->returnNews($obj, "欢迎关注中南民族大学官方微信", "点击进入民大简介", "http://bbs.scuec.edu.cn/scuecWechat/1/img/subscribe.jpg", "http://bbs.scuec.edu.cn/scuecWechat/1/scuec-about.html");
                break;
            case 'CLICK':
                $this->clickRouter($obj);
                break;
            default :
                break;
        }
    }
    
    private function chkPubKey($obj){
        $query = new \Wechat\Model\StudentModel();
        $chk = $query->chkPublicKey("".$obj->FromUserName);
        if ($chk==NULL) {
            return false;
        }
        else {
            return $chk;
        }
    }


    //点击事件路由
    private function clickRouter($obj){
        S(array('type'=>C('DATA_CACHE_TYPE')));
        if (!S($obj->FromUserName)){
            $this->doUpdate($obj->FromUserName);
//            exec("wget http://bbs.scuec.edu.cn/scuecWechat/index.php/wechat/update/updateg?key=$key -o /dev/null");
            S($obj->FromUserName,1,86400);
            S(($obj->FromUserName).'doing',1,60);
        }
        $start = microtime(true);
        switch ($obj->EventKey){
            //课表查询
            case 'classQuery':
                $info = $this->chkPubKey($obj);
                if (!$info){
                    $this->wechat->returnBindMsg($obj);
                }else {
                    $cla = new \Wechat\Model\ClaModel();
                    $tmp = $cla->where("`key` = '".$obj->FromUserName."'")->getField('id');
                    if (($tmp=="")or($tmp==null)){
                        if (!S(($obj->FromUserName).'doing')){
                            $this->doUpdate($obj->FromUserName);
                            S($obj->FromUserName,1,86400);
                            S(($obj->FromUserName).'doing',1,60);
                        }
                    }else{
                        $this->wechat->returnClassMsg($obj,0);
                    }
                    
                    
                }
                
                break;
            //考试查询
            case 'examQuery':
                $info = $this->chkPubKey($obj);
                if (!$info){
                    $this->wechat->returnBindMsg($obj);
                }else {
                    $exa = new \Wechat\Model\ExaModel();
                    $tmp = $exa->getExa($obj->FromUserName);
                    if (($tmp=="")or($tmp==null)){
                        if (!S(($obj->FromUserName).'doing')){
                            $this->doUpdate($obj->FromUserName);
                            S($obj->FromUserName,1,86400);
                            S(($obj->FromUserName).'doing',1,60);
                        }
                    }else{
                        $this->wechat->returnText($obj,$tmp);
                    }
                    
                }
                
                break;
            //座位查询
            case 'seatQuery':
                $info = $this->chkPubKey($obj);
                if (!$info){
                    $this->wechat->returnBindMsg($obj);
                }else {
                    $this->wechat->returnText($obj,"攻城狮正在努力的开发中。。。。。。");
                }
                break;
            //成绩查询
            case 'gradeQuery':
                $info = $this->chkPubKey($obj);
                if (!$info){
                    $this->wechat->returnBindMsg($obj);
                }else {
                    $gra = new \Wechat\Model\GraModel();
                    $tmp = $gra->getGra($obj->FromUserName);
                    if (($tmp=="")or($tmp==null)){
                        if (!S(($obj->FromUserName).'doing')){
                            $this->doUpdate($obj->FromUserName);
                            S($obj->FromUserName,1,86400);
                            S(($obj->FromUserName).'doing',1,60);
                        }
                    }else{
                        $this->wechat->returnText($obj,$tmp);
                    }
                    
                }
                break;
            //图书查询
            // case 'bookQuery':
            //     $info = $this->chkPubKey($obj);
            //     if (!$info){
            //         $this->wechat->returnBindMsg($obj);
            //     }else {
            //         $this->wechat->returnText($obj,"攻城狮正在努力的开发中。。。。。。");
            //     }
            //     break;

            //一卡通
            case 'cardQuery':
                $this->wechat->returnText($obj, "攻城狮正在努力的开发中。。。。。。");
                break;

            //------------我的民大-----------
            //新生导航
            case 'sNewstu':
                $data = array(array('title'=>'【新生指南】民大地图','content'=>'','picurl'=>'http://bbs.scuec.edu.cn/scuecWechat/1/img/map.jpg','url'=>'http://bbs.scuec.edu.cn/scuecWechat/1/scuec-map.html'),
                    array('title'=>'【新生指南】民大关键字','content'=>'','picurl'=>'http://bbs.scuec.edu.cn/scuecWechat/1/img/club.jpg','url'=>'http://bbs.scuec.edu.cn/scuecWechat/1/scuec-new-keywords.html'),
                    array('title'=>'【新生指南】民大生存攻略','content'=>'','picurl'=>'http://bbs.scuec.edu.cn/scuecWechat/1/img/market.jpg','url'=>'http://bbs.scuec.edu.cn/scuecWechat/1/scuec-new-life.html'),
                    array('title'=>'【新生指南】民大时刻表','content'=>'','picurl'=>'http://bbs.scuec.edu.cn/scuecWechat/1/img/about.jpg','url'=>'http://bbs.scuec.edu.cn/scuecWechat/1/scuec-new-time.html'));
                $this->wechat->returnMultiNews($obj, $data, 4);
                break;
            //校园助手
            case 'sHelper':
                $data = array(array('title'=>'【校园助手】竞赛指南','content'=>'','picurl'=>'http://bbs.scuec.edu.cn/scuecWechat/1/img/competition.jpg','url'=>'http://bbs.scuec.edu.cn/scuecWechat/1/scuec-asis-competition.html'),
                    array('title'=>'【校园助手】辅修及双学位','content'=>'','picurl'=>'http://bbs.scuec.edu.cn/scuecWechat/1/img/degree2.jpg','url'=>'http://bbs.scuec.edu.cn/scuecWechat/1/scuec-asis-degree.html'),
                    array('title'=>'【校园助手】校车时间表','content'=>'','picurl'=>'http://bbs.scuec.edu.cn/scuecWechat/1/img/school-bus1.jpg','url'=>'http://bbs.scuec.edu.cn/scuecWechat/1/scuec-asis-schoolbus.html'));
                $this->wechat->returnMultiNews($obj, $data, 3);
                break;
            default :
                break;

            //------------南湖资讯-----------
            case 'iMovie':
                $data = array(array('title'=>'【美食天地】巧克力食客','content'=>'','picurl'=>'http://mmbiz.qpic.cn/mmbiz/aOOh9W487MTrWMvZFicZz9muA1RQNtbSkDBHpDdE0U41mc68QFtLzsCHXHyb3OvnBhTpSzeapcpafCaVTfL9bGw/0','url'=>'http://mp.weixin.qq.com/s?__biz=MzA3NDc5NTEzOA==&mid=200887147&idx=3&sn=0f7cb7755f1639c5faa549978dbb0d6b&scene=4#wechat_redirect'),
                    array('title'=>'【音乐时光】欧洲乐迷新宠:指尖乐队（Finger Tips)','content'=>'','picurl'=>'http://mmbiz.qpic.cn/mmbiz/aOOh9W487MTyBpDW9WTLD51JETQka1KOAOsry2RGkpjOkJrwe13BRuNYTm5xCZjVCHZ0ZpyTvib6wBhBj260O4A/640','url'=>'http://mp.weixin.qq.com/s?__biz=MzA3NDc5NTEzOA==&mid=200884693&idx=2&sn=c14a089e99a0ca9493975c3c6cdfde54&scene=4#wechat_redirect'),
                    array('title'=>'【美食天地】国庆长假，带你一一走过武汉的美食街（一）','content'=>'','picurl'=>'http://mmbiz.qpic.cn/mmbiz/aOOh9W487MQ8sbiaYDpm2tIYbUlzRrBh8wsTU3sz8rdW0L5zKD8BwVuDJ6pY4Zpws9lfThQTfzRwvuxo7ISMTjg/640','url'=>'http://mp.weixin.qq.com/s?__biz=MzA3NDc5NTEzOA==&mid=200855546&idx=2&sn=d2b779e80054a3f6e65aa9b231690878&scene=4#wechat_redirect'),
                    array('title'=>'【音乐时光】陪九零年代成长的那个大男孩叫周杰伦','content'=>'','picurl'=>'http://mmbiz.qpic.cn/mmbiz/aOOh9W487MR7bJOqJha4tbNK47dhDeUu00OewibicFqNLUw3O1BnXicV4GKnQaBNTftKd7MV9AVlFIKcog39H32ibA/640','url'=>'http://mp.weixin.qq.com/s?__biz=MzA3NDc5NTEzOA==&mid=200851719&idx=2&sn=f3dbfecef5802353584f6a51867e4d61&scene=4#wechat_redirect'));
                $this->wechat->returnMultiNews($obj, $data, 4);
                break;
            case 'iLecture':
                $this->wechat->returnText($obj, "小编们正在努力准备精彩的文章。。。。。");
                break;
            case 'iEvent':
                $data = array(array('title'=>'【活动】情聚民大 梦圆南湖 “孔子学院日”文化活动周精彩活动尽显中国文化魅力','content'=>'','picurl'=>'http://mmbiz.qpic.cn/mmbiz/aOOh9W487MQPTUaZ3eT05qZajH31GfNZKbVLI5hMRibK1Gic2xAGUicnAcia2M7LlJHmOno1G6Aic2ZsPParEyzhEYA/0','url'=>'http://mp.weixin.qq.com/s?__biz=MzA3NDc5NTEzOA==&mid=200863852&idx=1&sn=312fe2c22116b34dc8236411f5569fdd&scene=4#wechat_redirect'),
                    array('title'=>'【活动】微信平台小名火热征集中','content'=>'','picurl'=>'http://mmbiz.qpic.cn/mmbiz/aOOh9W487MSHhiatfzzfyVVemPyFgGTCMY1Gy4qpdfVMG113aS2zHpQblEbuvz8FqMrokfVoEL3ibCwWoVS8DTXQ/640','url'=>'http://mp.weixin.qq.com/s?__biz=MzA3NDc5NTEzOA==&mid=200812175&idx=1&sn=f6c9a9d3bb9f859d6f3b7db184bb0c5f&scene=4#wechat_redirect'));
                $this->wechat->returnMultiNews($obj, $data, 2);
                break;      
            case 'iPush':
                $this->wechat->returnNews($obj, "【帮推】帮推功能正式上线啦！", "感谢大家对于中南民族大学官方微信平台的关注。为了给师生们带来更多更丰富的校园资讯，官微现推出【帮推】栏...", "http://mmbiz.qpic.cn/mmbiz/aOOh9W487MRn1zhLrGtM4lAa5zHdAkePyB0BF5LUedscVnoJbxC507Hq3EH2TUkCuUkQiarBovfy6Cyt1T41hNg/640", "http://mp.weixin.qq.com/s?__biz=MzA3NDc5NTEzOA==&mid=200838181&idx=2&sn=18c1f6c690277135332d029b016a939e#rd");
                break;
        }
    }


    private function doUpdate($key){
        exec("wget http://bbs.scuec.edu.cn/scuecWechat/index.php/wechat/update/index?key=$key -o /dev/null");
    }



    public function testexam(){
//        echo C('WECHAT_CUSTOMENU');
        $start = microtime(true);
        $query = new \Wechat\Model\DataqueryModel();
        $query->setKey("ogqZFt6fP_WzilD0O5m3CgyU5d_4");
         if ($query->login("10065030", "221100g0")){
             echo "ok\n";
             $query->jwCheck();
             $query->getExam();
         }else{
             echo "false";
         }
         $stop = microtime(TRUE);
         echo "<====>".($stop -$start);
        
    }
       public function testclass(){
//        echo C('WECHAT_CUSTOMENU');
        $start = microtime(true);
        $query = new \Wechat\Model\DataqueryModel();
        $query->setKey("ogqZFt6fP_WzilD0O5m3CgyU5d_4");
         if ($query->login("10065030", "221100g0")){
             echo "ok\n";
             $query->jwCheck();
             $query->getClassInfo();
         }else{
             echo "false";
         }
         $stop = microtime(TRUE);
         echo "<====>".($stop -$start);
        
    }
       public function testgrade(){
//        echo C('WECHAT_CUSTOMENU');
        $start = microtime(true);
        $query = new \Wechat\Model\DataqueryModel();
        $query->setKey("ogqZFt6fP_WzilD0O5m3CgyU5d_4");
         if ($query->login("10065030", "221100g0")){
             echo "ok\n";
             $query->jwCheck();
             $query->getMark();
         }else{
             echo "false";
         }
         $stop = microtime(TRUE);
         echo "<====>".($stop -$start);
        
    }

    /**
     * 微信验证
     */
    public function index(){
        $echoStr = I('get.echostr',"");
        if ($echoStr!=""){
            echo ($this->checkSignature())?$echoStr:"error1";
        }  else {
            $postData = $GLOBALS["HTTP_RAW_POST_DATA"];
            if ($postData!=""){
                $test = new \Wechat\Model\TestModel();                
                $postObj = simplexml_load_string($postData, 'SimpleXMLElement', LIBXML_NOCDATA);
                $test->create(array('value'=>$postObj->asXML()));
                $test->add();
                $this->router($postObj);
            }else {
                echo "";
            }
        }
    }
}